package com.test.platform.websocket;

import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class WebSocketService {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketService.class);
    private final ConcurrentHashMap<String, WebSocketSession> sessions = new ConcurrentHashMap<>();
    private final ObjectMapper objectMapper = new ObjectMapper();
    private Consumer<Boolean> confirmationCallback;

    public void addSession(String sessionId, WebSocketSession session) {
        sessions.put(sessionId, session);
        logger.info("WebSocket 会话已添加: {}", sessionId);
    }

    public void removeSession(String sessionId) {
        sessions.remove(sessionId);
        logger.info("WebSocket 会话已移除: {}", sessionId);
    }

    public void sendMessage(String type, WebSocketMessage message) {
        try {
            String jsonMessage = objectMapper.writeValueAsString(message);
            TextMessage textMessage = new TextMessage(jsonMessage);
            
            // 获取最新的活跃会话（如果有多个，只使用最后一个）
            WebSocketSession activeSession = sessions.values().stream()
                .filter(WebSocketSession::isOpen)
                .findFirst()
                .orElse(null);
            
            if (activeSession != null && activeSession.isOpen()) {
                try {
                    activeSession.sendMessage(textMessage);
                    logger.debug("消息已发送: {}", jsonMessage);
                } catch (IOException e) {
                    logger.error("发送消息失败: {}", e.getMessage());
                    removeSession(activeSession.getId());
                }
            }
        } catch (Exception e) {
            logger.error("消息序列化失败: {}", e.getMessage());
        }
    }

    public void setConfirmationCallback(Consumer<Boolean> callback) {
        this.confirmationCallback = callback;
    }

    public void handleConfirmation(boolean result) {
        if (confirmationCallback != null) {
            confirmationCallback.accept(result);
            confirmationCallback = null;
        }
    }

    public boolean hasActiveSessions() {
        return !sessions.isEmpty();
    }
}